<?php

namespace app\common\model;

use think\Model;
use app\common\model\Platform as PlatformModel;

use app\common\model\PlatformBalanceLog as PlatformBalanceLogModel;
use app\common\model\PlatformPushLog as PlatformPushLogModel;
use app\common\model\PlatformInfo as PlatformInfoModel;
use app\common\model\PlatformOptionValue as PlatformOptionValueModel;
use app\common\model\OptionValue as OptionValueModel;
use app\common\model\PlatformPushStatus as PlatformPushStatusModel;

use app\common\model\Info as InfoModel;
use push\Apibase;
use think\Db;
use think\facade\Cache;
use think\facade\Env;
use think\facade\Log;

class ApushModel extends Base
{
    protected $table = 'areas';
    public static $cacheTuisongPre = 'tsmd5';
    public static $cacheTuisongIng = 'tsingmd5';
    //接口过来的数据先走这里撞库
    public static function Zhuangku($mobileMd5, $city,$channel_id=0,$info=null)
    {
        addLog("撞库000:" . $mobileMd5 . '-----' . $city, 'zhuanfa');

        $cityCode = OptionValueModel::getCityAttr($city);
        if (!$cityCode) {
            addLog("城市不在库中:" . date('Y-m-d H:i:s') . '-----' . $city, 'zhuanfa');
            return false;
        }
        $platforms = PlatformModel::where('status', 1)->where('is_push', 1)->where("city_type=2 or find_in_set(" . $cityCode . ",citys)")->order("city_type asc,lunxun asc")->select();
        $apibase = new Apibase();
        $sumPlat = count($platforms);
        foreach ($platforms as $v) {
            // 工作时间限制
            if (date("H:i:s") < $v['push_start']) {
                addLog("撞库001:非工作时间" . $v['id'], 'zhuanfa');
                continue;
            }
            if (date("H:i:s") > $v['push_end']) {
                addLog("撞库002:非工作时间" . $v['id'], 'zhuanfa');
                continue;
            }
            $sumPlat--; //总数减一
            $v->lunxun += 1;
            $v->save();

            $quanguo =Env::get("environment.quanguo"); //全国标识
            // var_dump($quanguo,$yujiance);exit;
            if($quanguo){
                $yujiance=self::zizhiPre($info,$v);
                if($info&&!$yujiance){
                    logToTmp("quanguo","不符合条件--".$info['id'].'--'.$v['id']);
                    continue;
                }
            }
           //限制条数
            if ($v['day_limit'] > -1) {
                $logs = PlatformPushLogModel::where('platform_id',$v['id'])->where('c_time', '>=', date("Y-m-d 00:00:00"))->select()->toArray();
                if (count($logs) >= $v['day_limit'] ) {
                    continue;
                }
            }
            //渠道接口转发

            if ($v['is_api'] == 0) { //渠道非接口
                //装自己的库
                $info = Db::table('infos')->alias('t1')
                    ->leftJoin('platform_push_logs t2', 't1.id=t2.info_id')
                    ->where('t2.platform_id', $v['id'])->where('phone_md5', $mobileMd5)
                    ->field("t1.id")
                    ->order("t1.id desc")->find();
                if ($info) {
                    return false;
                }
                Cache::set(self::$cacheTuisongPre . $mobileMd5, $v['id'], 300);
                addLog("撞库001:无接口--成功", 'zhuanfa');
                return true;
            }
            $info['mobile'] = $mobileMd5;
            $tmpRst = $apibase->Zhuangku($v, $v['ename'], $info,$channel_id,$city);
            if ($tmpRst) {
                addLog("撞库:" . $mobileMd5 . "---" . $v['id'], 'zhuanfa');
                Cache::set(self::$cacheTuisongPre . $mobileMd5, $v['id'], 300);
                return true; //渠道符合，做个记录
            }
        }
        if ($sumPlat == 0) { //所有都撞库
            //没有渠道合适
            addLog("撞库:" . $mobileMd5 . "--无下游渠道", 'zhuanfa');
            return  false;
        }
        //存在部分渠道不在推送时间
        return 0;
    }
    //监测手机号撞库是否还在缓存当中,超时返回true
    public static function checkOffMobile($mobile){
        $platId = Cache::get(self::$cacheTuisongPre . md5($mobile));
        if (!$platId) {
            return true;
        }
        return false;
    }
    public static function zhuanfa($info)
    {
        //标记该订单正在转发中。不用多处理
        Cache::set(self::$cacheTuisongIng . $info['phone_md5'], $info['id'], 300);

        addLog("beg0:" . date('Y-m-d H:i:s') . '-----' . $info['id'], 'zhuanfa');
        // $platforms = PlatformModel::where('status', 1)->where('is_push', 1)->where('balance', '>', 0)->where("city_type=2 or find_in_set(" . $info['province'] . ",citys)")->order("city_type asc,lunxun asc")->select();
        $platId = Cache::get(self::$cacheTuisongPre . $info['phone_md5']);
        if (!$platId) {
            addLog("beg0:" . date('Y-m-d H:i:s') . '---无下游--' . $info['id'], 'zhuanfa');
            return false;
        }
        $platform = PlatformModel::where('id', $platId)->find();
        $pushSuccess = self::push($info, $platform, $info['province']);
        if ($pushSuccess) {
            InfoModel::where('id', $info['id'])->update(['platform_id' => $platId]);
            if ($platform['sms_power'] == 1) { //发送短信开关
                self::sendSmsToPlant($platId);
            }
            self::sendSmsToCustomer1($info['phone'],$info['apply_name'],$info['sex']);
            return true;
        }
        // if (!empty($platforms)) {
        //     foreach ($platforms as $key => $platform) {
        //         $platform->lunxun+=1;
        //         $platform->save();
        //         $pushstatus = PlatformPushStatusModel::where('info_id', $info['id'])->where('platform_id', $platform['id'])->find();
        //         if (!$pushstatus ) {//&& $info['create_time'] > $platform['update_time']
        //           $pushSuccess=self::push($info, $platform, $info['province']);
        //           if($pushSuccess){
        //             return true;
        //           }
        //         }
        //     }
        // }
        // addLog("beg0:没有合适渠道",'zhuanfa');
        return false;
    }
    //给甲方发短信
    public static function sendSmsToPlant($plantformId = 0)
    {
        $allPlat = PlatformAccount::BaseAll(['platform_id' => $plantformId,'is_system'=>1]);
        $smsConf = array(
            'key'   => Env::get("juhe.key"), //您申请的APPKEY
            // 'mobile'    => $mobile, //接受短信的用户手机号码
            'tpl_id'    => Env::get("juhe.jia_tongzhi"), //您申请的短信模板ID，根据实际情况修改
            // 'tpl_value' =>'#code#='.$code //您设置的模板变量，根据实际情况修改
        );

        foreach ($allPlat as $v) {
            $smsConf['mobile'] = $v['account'];
            juheYzmcurl($smsConf);
        }
    }
     //给客户第一次发短信
     public static function sendSmsToCustomer1($mobile = 0,$name="",$sex=1)
     {
        $tpl_id=Env::get("juhe.customer_tongzhi1");
        if(!$tpl_id){
            return false;
        }
         $smsConf = array(
             'key'   => Env::get("juhe.key"), //您申请的APPKEY
             // 'mobile'    => $mobile, //接受短信的用户手机号码
             'tpl_id'    => $tpl_id, //您申请的短信模板ID，根据实际情况修改
             // 'tpl_value' =>'#code#='.$code //您设置的模板变量，根据实际情况修改
         );
         $smsConf['mobile'] =$mobile;
         $xing=mb_substr($name,0,1);
         if($sex==2){
            $xing.="女士";
         }else{
            $xing.="先生";
         }
         $vars['name'] =$xing;
         $smsConf['vars']=json_encode($vars,JSON_UNESCAPED_UNICODE);
         juheYzmcurl($smsConf);
     }
     //给客户第一次发短信
     public static function sendSmsToCustomer2($mobile = 0,$name="",$sex=1,$company='')
     {
        $tpl_id=Env::get("juhe.customer_tongzhi2");
        if(!$tpl_id){
            return false;
        }
         $smsConf = array(
             'key'   => Env::get("juhe.key"), //您申请的APPKEY
             // 'mobile'    => $mobile, //接受短信的用户手机号码
             'tpl_id'    => $tpl_id, //您申请的短信模板ID，根据实际情况修改
             // 'tpl_value' =>'#code#='.$code //您设置的模板变量，根据实际情况修改
         );
         $smsConf['mobile'] =$mobile;
         $xing=mb_substr($name,0,1);
         if($sex==2){
            $xing.="女士";
         }else{
            $xing.="先生";
         }
         $vars['name'] =$xing;
         $vars['company'] =$company;
         $smsConf['vars']=json_encode($vars,JSON_UNESCAPED_UNICODE);
         juheYzmcurl($smsConf);
         return true;
     }
    public static function push($info, $platform, $cityid)
    {
        addLog("beg1:" . date('Y-m-d H:i:s') . '--' . $info['id'] . '--' . $platform['id'], 'zhuanfa');

        if (empty($platform)) {
            return;
        }
        if ($platform->status == 0) {
            return;
        }
        if ($platform->is_push != 1) {
            return;
        }
        // $platform_info = PlatformInfoModel::get(array('platform_id' => $platform->id));

        // if (empty($platform_info)) {
        //     return;
        // }
        // if ($platform_info->status != 1) {
        //     return;
        // }

        // $info = InfoModel::where('id', $info['id'])->find();
        // if (!$info || $info['auto_nums'] > 0) return;

        $platform_option_values = PlatformOptionValueModel::where('platform_id', $platform->id)->select()->toArray();

        $temp = array();
        $tempprovince = array();
        if (!empty($platform_option_values)) {
            foreach ($platform_option_values as $key => $platform_option_value) {
                //城市单列
                if ($platform_option_value['option_item_ename'] == 'province') {
                    $tempprovince[] = $platform_option_value['option_value_value'];
                } else {
                    $temp[$platform_option_value['option_item_ename']][] = $platform_option_value['option_value_value'];
                }
            }
        }

        $option_values = $temp;

        $provincearray = $tempprovince;

        //多个勾选，多个限制
        if ($platform->push_type == 1) {
            $returnflag = false;
            if (count($option_values)) {
                foreach ($option_values as $key => $option_value) {
                    if (count($option_value) <= 0) {
                        continue;
                    }
                    if (!in_array($info[$key], $option_value)) {
                        $returnflag = true;
                        break;
                    }
                }
            }
        }
        //满足一个就推送
        if ($platform->push_type == 2) {
            $returnflag = true;
            if (count($option_values)) {
                foreach ($option_values as $key => $option_value) {
                    if (count($option_value) <= 0) {
                        continue;
                    }
                    if (in_array($info[$key], $option_value)) {
                        $returnflag = false;
                        break;
                    }
                }
            }
        }

        if ($returnflag) {
            return false;
        }

        // var_dump($info);exit();

        $infos = array($info);
        if (!empty($infos)) {

            foreach ($infos as $key => $value) {

                $push_api_flag = false;

                $begintime = strtotime(date('Y-m-d') . ' ' . $platform->push_start);
                $endtime = strtotime(date('Y-m-d') . ' ' . $platform->push_end);
                $nowtime = time();
                //账户余额不够支付的
                // if ($platform->balance < $platform->per_price) {
                //     return false;
                // }
                //触发条数限制和推送时间限制的也剔除掉
                if ($platform->day_limit > -1) {

                    $logs = PlatformPushLogModel::where('platform_id', $platform->id)->where('status_time', '>=', $begintime)->where('status_time', '<=', $endtime)->select()->toArray();
                    if (count($logs) >= $platform->day_limit || !($nowtime >= $begintime && $nowtime <= $endtime)) {
                        return false;
                    }
                }

                //记录推送状态
                //前置提交结束，记录推送状态
                $platform_push_status = new PlatformPushStatusModel();

                $platform_push_status->platform_id = $platform['id'];
                $platform_push_status->info_id = $value['id'];
                $platform_push_status->member_id = $value['member_id'];
                $platform_push_status->status_time = $platform_push_status->create_time = time();
                $platform_push_status->push_status = 0;

                //平台API推送
                if ($platform->is_api == 1) {
                    addLog("api0:" . date('Y-m-d H:i:s') . '--' . $platform->ename, 'zhuanfa');
                    $apibase = new Apibase();
                    $result = $apibase->CallAPI($platform, $platform->ename, $value);
                    addLog("api1:" . date('Y-m-d H:i:s') . '--' . $platform->ename . '--' . json_encode($result, JSON_UNESCAPED_UNICODE), 'zhuanfa');
                    if (!$result['result']) {
                        //如果API推送打开，未推送成功，则不记录任何信息
                        $platform_push_status->api_status = 0;
                        $platform_push_status->remark = $result['msg'];
                        $platform_push_status->save();
                        //自动推送+1
                        $newinfo = InfoModel::get(array('id' => $value['id']));
                        $newinfo->auto_nums = $newinfo->auto_nums + 1;
                        $newinfo->push_status = 'f';
                        $newinfo->save();
                        return false;
                    } else {
                        $push_api_flag = true;
                        //记录推送状态
                        $platform_push_status->api_status = 1;
                    }
                }else{
                    //没有接口，加入子后台表
                    $infoPlatObj = new InfoPlatModel();
                    $infoPlatObj['info_id'] = $value['id'];
                    $infoPlatObj['plat_id'] = $platform['id'];
                    $infoPlatObj['user_id'] = 0;
                    $infoPlatObj->save();
                }

                $platform_push_status->save();
                //成功后记录推送记录
                addLog("trans0:" . date('Y-m-d H:i:s') . '--' . $platform->ename, 'zhuanfa');
                Db::transaction(function () use ($value, $platform, $push_api_flag) {

                    $platform_push_log = new PlatformPushLogModel();

                    //扣除费用
                    $platform_balance_log = new PlatformBalanceLogModel();
                    $platform_balance_log->balance_before = $platform->balance;
                    $platform->balance -= $platform->per_price;
                    $platform_balance_log->balance_after = $platform->balance;
                    $platform_balance_log->remark = '推送扣除金额';
                    $platform->save();
                    //扣费结束
                    $platform_balance_log->platform_id = $platform->id;
                    $platform_balance_log->money = $platform->per_price;
                    $platform_balance_log->create_time = time();
                    $platform_balance_log->save();


                    $platform_push_log->platform_id = $platform->id;
                    $platform_push_log->info_id = $value['id'];
                    $platform_push_log->member_id = $value['member_id'];
                    $platform_push_log->platform_type = $platform->platform_type;
                    $platform_push_log->status_time = $platform_push_log->create_time = time();
                    $platform_push_log->money = $platform->per_price;
                    $platform_push_log->api = $push_api_flag ? 1 : 0;
                    $platform_push_log->save();

                    //更新推送状态
                    $newpushstatus = PlatformPushStatusModel::get(array('platform_id' => $platform->id, 'info_id' => $value['id']));
                    $newpushstatus->push_status = 1;
                    $newpushstatus->save();

                    //成功后自动推送+1
                    $newinfo = InfoModel::get(array('id' => $value['id']));
                    $newinfo->auto_nums = $newinfo->auto_nums + 1;
                    $newinfo->push_status = 's';
                    $newinfo->save();
                    return true;
                });
                addLog("trans1:" . date('Y-m-d H:i:s') . '--' . $platform->ename, 'zhuanfa');
            }
            return true;
        }
        return false;
    }
    //检测资质
    private  static function zizhiPre($info, $platform){
        if(!$info){//没有用户信息，默认通过
            return true;
        }

        $platform_option_values = PlatformOptionValueModel::where('platform_id', $platform->id)->select()->toArray();

        $temp = array();
        $tempprovince = array();
        if (!empty($platform_option_values)) {
            foreach ($platform_option_values as $key => $platform_option_value) {
                //城市单列
                if ($platform_option_value['option_item_ename'] == 'province') {
                    $tempprovince[] = $platform_option_value['option_value_value'];
                } else {
                    $temp[$platform_option_value['option_item_ename']][] = $platform_option_value['option_value_value'];
                }
            }
        }

        $option_values = $temp;
         //多个勾选，多个限制
         if ($platform->push_type == 1) {
            $returnflag = false;
            if (count($option_values)) {
                foreach ($option_values as $key => $option_value) {
                    if (count($option_value) <= 0) {
                        continue;
                    }
                    if (!in_array($info[$key], $option_value)) {
                        $returnflag = true;
                        break;
                    }
                }
            }
        }
        //满足一个就推送
        if ($platform->push_type == 2) {
            $returnflag = false;
            if (count($option_values)) {
                foreach ($option_values as $key => $option_value) {
                    if (count($option_value) <= 0) {
                        continue;
                    }
                    if (in_array($info[$key], $option_value)) {
                        $returnflag = true;
                        break;
                    }
                }
            }
        }
        //满足转发条件
        if ($returnflag) {
            return true;
        }
        //不满足转发条件
        return false;
    }
    
}
